<script setup name="banners">
import { reactive, ref } from "vue"
import { ChangeHeaderIndex, resetHeaderIndex, toast } from "@/composables/util"
import { readGoods, setGoodsBanner } from "@/api/goods"
import ChooseImage from "@/components/ChooseImage.vue"

defineProps({
  appendToBody: {
    type: Boolean,
    default: false
  }
})
// 表单数据
const form = reactive({
  banners: []
})
// 隐藏/显示对话框
const showDialog = ref(false)
// 加载
const loading = ref(false)
// 当前商品id
const goodsId = ref(0)
const emit = defineEmits(["reload"])

// 显示对话框
const open = async row => {
  ChangeHeaderIndex()
  showDialog.value = true
  loading.value = true
  goodsId.value = row.id
  const res = await readGoods(goodsId.value)
  form.banners = res.goodsBanner.map(v => v.url)
  loading.value = false
}
// 提交
const submit = async () => {
  try {
    loading.value = true
    await setGoodsBanner(goodsId.value, form)
    toast("设置轮播图成功！")
    emit("reload")
    close()
  } finally {
    loading.value = false
  }
}

const close = () => {
  showDialog.value = false
  form.banners.length = 0
  resetHeaderIndex()
}

// 向外导出方法
defineExpose({ open })
</script>

<template>
  <el-dialog class="banner-dialog" title="设置轮播图" v-model="showDialog" width="54%" destroy-on-close append-to-body :close-on-click-modal="false" :show-close="false">
    <el-form :model="form" v-loading="loading">
      <el-form-item label="轮播图">
        <ChooseImage :limit="9" v-model="form.banners" />
      </el-form-item>
    </el-form>
    <div class="actions">
      <el-button type="primary" @click="submit">提交</el-button>
      <el-button @click="close">取消</el-button>
    </div>
  </el-dialog>
</template>

<style lang="scss" scoped>
.banner-dialog {
  .actions {
    margin-top: 20px;
    text-align: center;
  }
}
</style>
